/**
 * @copyright 朱言俊
 * @link http://www.zhuyanjun.cn/
 * @create Created on 2020/5/8
 */
'use strict';

var appJsI18n;
var AppApi = function (){

  /**
   * 通用滑块
   *
   * 参数配置
   * 用data-*可进行配置
   *
   * 事件
   * data-{{init,change,changeEnd}}(swiper) 表示对应事件
   *
   * 特殊配置
   * data-animate 启用swiper.animate动画，需页面手动引入swiper.animate1.0.3.min.js和animate.min.css
   * data-{{prev,next,pagination}} swiper对应按钮和指示器的类或id
   */
  var slide = function (){
    $('.js-slide').each(function () {
      var $this = $(this),_data = $this.data();
      if (typeof _data.swiper !== 'undefined') return;
      swiperParallaxHandle($this);

      var enableAnimate = false;
      if(_data.animate){
        enableAnimate = _data.animate;
        delete _data.animate;
      }

      // 扩展init和change事件
      var changeEvent,initEvent,changeEndEvent;
      if(typeof _data.change === 'string'){
        changeEvent = _data.change;
        delete _data.change;
      }
      if(typeof _data.init === 'string'){
        initEvent = _data.init;
        delete _data.init;
      }
      if(typeof _data.changeEnd === 'string'){
        changeEndEvent = _data.changeEnd;
        delete _data.changeEnd;
      }

      $.each(_data,function (k,v){
        if(typeof v==='string' && v.indexOf('{') === 0){
          _data[k] = JSON.parse(v);
        }
      })

      var _config = $.extend({
        speed:600,
        lazy: {
          loadPrevNext: true,
        },
        pagination: _data.pagination || {el: $this.find('.swiper-pagination')},
        navigation: _data.navigation || {nextEl: $this.find('.swiper-button-next'), prevEl:$this.find('.swiper-button-prev'),},
        observer: true,
        observeParents: true,
        on:{
          init:function (){
            if(enableAnimate && typeof swiperAnimateCache === 'function' && swiperAnimate === 'function'){
              swiperAnimateCache(this);
              swiperAnimate(this);
            }
            if(initEvent){
              eval(initEvent+"(this)");
            }
          },
          slideChange:function (){
            if(changeEvent){
              eval(changeEvent+"(this)");
            }
          },
          slideChangeTransitionEnd:function (){
            if(enableAnimate && typeof swiperAnimate === 'function'){
              swiperAnimate(this);
            }
            if(changeEndEvent){
              eval(changeEndEvent+"(this)");
            }
          },
          beforeDestroy: function(){
            $this.removeData('swiper');
          },
        }
      },_data);
      var obj = new Swiper(this, _config);
      $this.data('swiper',obj);
    });
  }

  /**
   * 在swiper内，让内容支持视差滚动
   * @param $parent
   */
  var swiperParallaxHandle = function ($parent){
    var $el;
    if(typeof $parent === 'undefined'){
      $el = $('.js-parallax-handle');
    }else{
      $el = $parent.find('.js-parallax-handle');
    }
    $el.each(function (){
      var $this = $(this),
          start = $this.data('start') || 0,
          step = $this.data('step') || 2000;
      $this.children().each(function (i,n){
        $(n).attr('data-swiper-parallax',(start + step*i)*-1);
      });
    });
  }

  /**
   * 检测是否为移动设备
   * @returns {boolean}
   */
  var isMobile = function (){
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  }

  return {
    slide:slide,
    swiperParallaxHandle:swiperParallaxHandle,
    isMobile:isMobile
  }
}();

$(function () {
  if(typeof $window === 'undefined') $window = $(window);

  /**
   * 通用滑块
   */
  AppApi.slide();

  /**
   * 加上此类可以阻止事件冒泡
   */
  $('.js-cancel-bubble').click(function (e){
    if (window.event) {
      window.event.cancelBubble = true;
    } else {
      e.stopPropagation();
    }
  });

  /**
   * 滚动页面，导航条激活
   */
  var $header = $('header');
  $window.scroll(function (){
    if($window.scrollTop() > ($header.data('top') || 10)){
      if(!$header.hasClass('active')) $header.addClass('active')
    }else if($header.hasClass('active')){
      $header.removeClass('active')
    }
  });

  /**
   * banner
   */
  $('.js-banner').each(function (){
    var $this = $(this);
    if($this.data('swiper')) return;

    var slideChange = function (obj){
      if(typeof obj === 'undefined') obj = this;
      var $currSwiper = $(obj.slides[obj.activeIndex]),
          $video = $currSwiper.find('video');
      if($video.length){
        obj.autoplay.stop();
        $video.get(0).play();
        if(!$video.data('listen')){
          $video.data('listen',true);
          $video.get(0).addEventListener('ended', function() {
            if(obj.slides.length > 1){
              obj.slideNext();
              obj.autoplay.start();
            }else{
              $video.get(0).play();
            }
          });
        }
      }else{
        if(!obj.autoplay.running){
          setTimeout(function (){
            obj.autoplay.start();
          },310);
        }
      }

      $.each(obj.slides,function (i,n){
        var $n = $(n);
        if($n.hasClass('swiper-slide-active')) return;
        var $v = $n.find('video');
        if($v.length) $v.get(0).pause();
      });
    };

    var obj = new Swiper (this, {
      lazy: {
        loadPrevNext: true
      },
      loop: $this.find('.swiper-slide').length>1,
      pagination: {
        el: $this.find('.swiper-pagination')
      },
      navigation: {
        nextEl: $this.find('.swiper-button-next'),
        prevEl: $this.find('.swiper-button-prev')
      },
      parallax: true,
      observer: true,
      observeParents: true,
      speed:800,
      //autoHeight:true,
      autoplay: {
        delay: 5000,
        disableOnInteraction:false,
        pauseOnMouseEnter:true
      },
      on:{
        init:function (){
          setTimeout(function (){
            obj.autoplay.stop();
          },300);
          $this.css('min-height','auto');
          if(this.slides.length === 1) slideChange(this);
        },
        slideChangeTransitionStart: slideChange,
        transitionEnd:function (){
          $.each(this.slides,function (i,n){
            var $n = $(n),
                $v = $n.find('video');
            if($v.length){
              if($n.hasClass('swiper-slide-active')){
                $v.get(0).play();
              }else{
                $v.get(0).pause();
              }
            }
          });
        }
      }
    });
    $this.data('swiper',obj);
  });

  /**
   * 滚动动画
   */
  AOS.init({
    once:true,
    offset: 100,
    duration: 600,
    delay: 100,
  });

  var resizeTimer;
  $window.resize(function (){
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function (){
      AOS.refresh();
    },20)
  });

  /**
   * 移动端主导航展开监听
   */
  $('#navbar').on('hidden.bs.collapse', function () {
    $(this).parents('.navbar').removeClass('navbar-open');
  }).on('show.bs.collapse', function () {
    $(this).parents('.navbar').addClass('navbar-open');
  }).find('.dropdown').hover(function (){
    if(!AppApi.isMobile() && $window.width() > 991.98)
      $(this).find('[data-toggle="dropdown"]').dropdown('show');
  },function (){
    if(!AppApi.isMobile() && $window.width() > 991.98)
      $(this).find('[data-toggle="dropdown"]').dropdown('hide');
  })

  /**
   * 惰加载
   */
  lazyload();

  /**
   * 移动端视频播放
   */
  $('.js-play-video').click(function (){
    var $this = $(this),src = $this.data('video');
    if(!src) return;
    var $parent = $this.parent();
    var $swiper = $parent.parents('.swiper-container'),swiperObj;
    if($swiper.length) {
      swiperObj = $swiper.data('swiper');
      swiperObj.autoplay.stop();
    }
    var size = [];
    if(typeof $window === 'undefined') $window = $(window);
    var widowWidth = $window.width();
    if(widowWidth<576){
      size = ['345px', '200px'];
    }else if(widowWidth<768){
      size = ['500px','282px'];
    }else if(widowWidth<992){
      size = ['700px','394px'];
    }else{
      size = ['8rem','4.5rem'];
    }
    layer.open({
      id:"layer-mobile-video",
      type:1,
      title:false,
      shade:0.8,
      area:size,
      content:'<video style="display: block;object-fit: contain;background-color: #000;width: 100%;height:100%" poster="'+$parent.find('img').attr('src')+'" controls><source src="'+src+'" type="video/mp4"></video>',
      end:function (){
        if(swiperObj){
          swiperObj.autoplay.start();
        }
      }
    })
  });

  /**
   * 锚链接跳转
   */
  $('body').on('click','.js-anchor-jump',function (){
    var $target = $($(this).data('target') || $(this).attr('href'));
    $('html,body').animate({
      scrollTop:$target.length?$target.offset().top - $('header').height():0
    },300);
    return false;
  });

  // 表单提交
  $('#js-form').on('beforeSubmit', function (e) {
    // 可在全局定义，进行国际化处理
    if(typeof appJsI18n === 'undefined') appJsI18n = {
      'confirm':'确认',
      'info':'信息',
      'requestFailed':'请求失败',
      'submitSuccess':'提交成功',
    };
    var $form = $(this);
    var loading = layer.load(2);
    $.ajax({
      type:$form.attr('method'),
      url: $form.attr('action'),
      dataType:'json',
      data:$form.serialize(),
      complete:function(){
        layer.close(loading);
      },
      error:function(){
        layer.alert(appJsI18n.requestFailed,{icon:2,title:appJsI18n.info,btn:[appJsI18n.confirm]});
      },
      success:function (res) {
        if(res.status){
          layer.alert(appJsI18n.submitSuccess,{icon:1,title:appJsI18n.info,btn:[appJsI18n.confirm]});
          $form[0].reset();
        }else{
          layer.alert(res.message,{icon:2,title:appJsI18n.info,btn:[appJsI18n.confirm]});
        }
      }
    });
  }).on('submit', function (e) {
    e.preventDefault();
  });
});
